import { Table } from 'antd';
import { get } from 'lodash';
import React, { useEffect, useMemo, useState } from 'react';
import { useFetch } from '../../../hooks/useFetch';
/**
 * 通用table
 */
export const CommonTable = React.memo(function (props) {
    const { columns, form, dataFieldKey = 'data', totalFieldKey = 'total', value, ajaxFn, onChange, formatForm, onValueChange, ...args } = props;
    const [paginationState, setPaginationState] = useState({
        page: 1,
        pageSize: 10,
    });
    const { fetch, data = {}, loading, updateData, } = useFetch(ajaxFn ||
        (() => Promise.resolve({
            [dataFieldKey]: value,
            [totalFieldKey]: 0,
        })), {}, true);
    const total = get(data, totalFieldKey) || 0;

    const dataSource = get(data, dataFieldKey) || [];
    const searchForm = useMemo(() => {
        const req = {
            ...form,
            ...paginationState,
        };
        return formatForm ? formatForm(req) : req;
    }, [paginationState, form]);
    useEffect(() => {
        // console.log('[table flush]', searchForm);
        fetch(searchForm).then((res) => {
            onValueChange?.(get(res, dataFieldKey) || []);
        });
    }, [ajaxFn, searchForm]);
    useEffect(() => {
        updateData({
            [dataFieldKey]: value,
            [totalFieldKey]: total,
        });
    }, [value]);
    return (<Table size="middle" bordered headerBorderRadius={0} stickyScrollBarBorderRadius={0} loading={loading} columns={columns} dataSource={dataSource} pagination={args.pagination === false
            ? false
            : {
                total,
                current: searchForm.page,
                pageSize: searchForm.pageSize,
                showSizeChanger: true,
                showTotal: (total) => `总数：${total}`,
                ...args.pagination,
                onChange(page, pageSize) {
                    const newPaginationState = {
                        page,
                        pageSize,
                    };
                    setPaginationState(newPaginationState);
                    onChange?.({
                        ...searchForm,
                        ...newPaginationState,
                    });
                    args.pagination && args.pagination.onChange?.(page, pageSize);
                },
            }} {...args}/>);
});
export default CommonTable;
